package com.steven.logserver.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

/**
 * ES 配置
 *
 * @author qinxh
 * @date 2020/09/01
 */
@Configuration
public class ElasticsearchConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchConfig.class);
    /**
     * 集群地址
     */
    @Value("${elasticsearch.cluster.nodes}")
    private String nodes;

    /**
     * 集群名称
     */
    @Value("${elasticsearch.cluster.name}")
    private String clusterName;

    /**
     * 连接池
     */
    @Value("${elasticsearch.pool}")
    private String poolSize;

    @Bean
    public TransportClient init() {

        TransportClient transportClient = null;
        try {
            // 1. 配置信息
            Settings esSetting = Settings.builder()
                    .put("cluster.name", clusterName)
                    /* 增加嗅探机制，找到ES集群*/
                    .put("client.transport.sniff", true)
                    /* 设置线程池个数，暂时设为10*/
                    .put("thread_pool.search.size", Integer.parseInt(poolSize))
                    .build();
            transportClient = new PreBuiltTransportClient(esSetting);
            // 2. 添加集群地址
            if (!"".equals(nodes)){
                String s = ",";
                for (String node:nodes.split(s)) {
                    String[] initSocket  = node.split(":");
                    String address = initSocket[0];
                    int port = Integer.valueOf(initSocket[1]);
                    transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(address), port));
                }
            }
        } catch (Exception e) {
            LOGGER.error("初始化 TransportClient 对象失败!", e);
        }

        return transportClient;
    }
}
